package fr.umlv.projet.android.subject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import ae.javax.xml.bind.JAXBContext;
import ae.javax.xml.bind.JAXBException;
import ae.javax.xml.bind.Unmarshaller;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import fr.umlv.projet.android.andex.R;
import fr.umlv.projet.android.messaging.MessagingActivity;
import fr.umlv.projet.android.parser.jaxb.Exam;
import fr.umlv.projet.android.parser.jaxb.Node;
import fr.umlv.projet.android.submit.SubmitActivity;
import fr.umlv.projet.android.utils.FileUtils;
import fr.umlv.projet.android.utils.StringUtils;

public class SubjectPlaneActivity extends ListActivity {

	private NodeArrayAdapter adapter;
	private static final int ITEM_REQUEST = 1734;
	private ArrayList<Node> list;
	private int curPos;
	private String examName;
	private int countAnswered;
	
	private void traversal(List<Node> nodes, String indent, String parent){
		for(Node n: nodes){
			n.setTitle(indent + n.getTitle());
			list.add(n);
			if(parent.equals("")){
				n.setPath(n.getTitle().trim());
			}
			else{
				n.setPath(parent + "/" + n.getTitle().trim());
			}
			traversal(n.getNode(), indent + "  ", n.getPath());
		}
	}

	private void parseSubject(InputStream is) {
		JAXBContext jc;
		Exam exam = null;
		try {
			jc = JAXBContext.newInstance("fr.umlv.projet.android.parser.jaxb");
			Unmarshaller unmarshaller = jc.createUnmarshaller();
			exam = (Exam) unmarshaller.unmarshal(is);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		examName = exam.getTitle();
		setTitle(getTitle() + ": " + examName);
		traversal(exam.getNode(), "", "");
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		String exam = getIntent().getExtras().getString("exam");

		list = new ArrayList<Node>();
		try {
			parseSubject(StringUtils.stringToInputStream(exam));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		adapter = new NodeArrayAdapter(this,
				android.R.layout.simple_list_item_1, android.R.id.text1, list);

		setListAdapter(adapter);
		
		countAnswered = 0;
		
		// Clean old submissions :
		String str = Environment.getExternalStorageDirectory().getAbsolutePath();
		File folderToDelete = new File(str+"/Andex");
		try {
			FileUtils.delete(folderToDelete);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == ITEM_REQUEST) {
			switch (resultCode) {
			case ItemActivity.RESULT_NEXT:
				launchItem(curPos+1);
				break;
			case ItemActivity.RESULT_PREVIOUS:
				launchItem(curPos-1);
				break;
			case ItemActivity.RESULT_VALIDATE:
				Node node = (Node) getListView().getItemAtPosition(curPos);
				if(!node.isAnswered()){
					node.setAnswered(true);
					adapter.notifyDataSetChanged();
					countAnswered++;
				}
				if(countAnswered == list.size()){
					new AlertDialog.Builder(this).setTitle("Finish")
							.setMessage("You have finished answering the exam.\nWant to send the answers now?")
							.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int id) {
									Intent submitActivity = new Intent(getBaseContext(), SubmitActivity.class);
									submitActivity.putExtra("exam", examName);
									
									startActivity(submitActivity);
									finish();
								}
							})
							.setNegativeButton("No",new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int id) {
									dialog.cancel();
								}
							}).show();
				}
				break;
			default:
				break;
			}
		}
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		launchItem(position);
	}

	private void launchItem(int position) {
		curPos = position;
		Node selectedValue = (Node) getListAdapter().getItem(position);
		Intent intent = new Intent(this, ItemActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("node", selectedValue);
		intent.putExtra("buttonPreviousInvisible", position == 0);
		intent.putExtra("buttonNextInvisible", position == (getListAdapter().getCount()-1));
		intent.putExtra("examName", examName);
		startActivityForResult(intent, ITEM_REQUEST);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.subject_plane, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId())
        {
        case R.id.messaging:
        	Intent messagingActivity = new Intent(getBaseContext(), MessagingActivity.class);
        	messagingActivity.putExtra("exam", examName);
        	
            startActivity(messagingActivity);
            return true;
 
        default:
            return super.onOptionsItemSelected(item);
        }
	}

}
